<template>
  <div class="item-bg air">
    <div class="on-off">
      <!--模拟量数据-->
      <div class="simulate-value" v-for="(simulateValue, index) in simulateValues" :key="index" :class="`simulate-value${simulateValue.id}`" :style="{ color: simulateValue.color}">
        {{ simulateValue.value }}
      </div>
    </div>
    <el-dialog
      v-for="(warn, index) in activeWarnings"
      :key="`${warn.id}-${warn.type}-${index}`"
      v-model="warn.visible"
      :title="`警告 - ${warn.deviceName} ${labelMap[warn.type]}信号`"
      :modal-class="'custom-warning-dialog'"
      width="400px"
      draggable
      :show-close="false"
      :style="{ 
        top: `${warn.topOffset}px`, 
        left: warn.leftOffset 
      }"
    >
    <!--   <span>检测到 {{ warn.deviceName }} 报警：{{ labelMap[warn.type] }} 信号</span> -->
      <template #footer>
        <el-button
          @click="removeDialog(warn)"
          style="background-color: #000; color: white; border: none"
        >
          关闭
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
<style src="../image.css"></style>
<script setup>
import { ref, computed,reactive } from 'vue';
import initData from "../../initData"
const { socket } = initData(true);
import bus from '../../utils/bus';
const msg = ref('');
//创建模拟量的初始值
const simulateValues = ref([
  { id: 16, value: ref(111 + 'MPa') },
  { id: 20, value: ref(111 + 'kPa') },
  //温度传感器
  { id: 17, value: ref(111 + 'C°') },
  { id: 18, value: ref(111 + 'C°') },
  { id: 21, value: ref(111 + 'C°') },
  //电磁流量
  { id: 15, value: ref(111 + "m³/h") },
  { id: 19, value: ref(111 + 'm³/h') },
  //大气湿度
  { id: 22, value: ref(111)  + '%RH'},
])
//报警设备
const warnings = ref([
  { id: 0, name: '管路流量报警', low: false, hight: false, err: false },
  { id: 2, name: '压力报警', low: false, hight: false, err: false },
  { id: 4, name: '温度报警', low: false, hight: false, err: false },
  { id: 6, name: '露点报警', low: false, hight: false, err: false },
  { id: 8, name: '空气流量报警', low: false, hight: false, err: false },
  { id: 10, name: '大气压力报警', low: false, hight: false, err: false },
  { id: 12, name: '大气温度报警', low: false, hight: false, err: false },
  { id: 14, name: '大气湿度报警', low: false, hight: false, err: false },
]);
const labelMap = {
  low: '低',
  high: '高',
  err: '故障'
};

// 当前活动弹窗列表
const activeWarnings = ref([])

// 冷却时间限制
const warningPopupCooldowns = reactive({
  low: 0,
  high: 0,
  err: 0
})
const popupDelay = 30000 // 30秒

const showDialog = (type, deviceName, id) => {
  const now = Date.now()
  const cooldownKey = `${type}-${id}`
  
  if (now - (warningPopupCooldowns[cooldownKey] || 0) < popupDelay) return
  warningPopupCooldowns[cooldownKey] = now

  // 动态计算位置
  const visibleCount = activeWarnings.value.length
  const top = 0 + (visibleCount % 3) * 130
  const left = 31 + Math.floor(visibleCount / 3) * 30 + '%'

  activeWarnings.value.push({
    id,
    type,
    deviceName,
    visible: true,
    topOffset: top,
    leftOffset: left
  })
}

const removeDialog = (warn) => {
  const index = activeWarnings.value.indexOf(warn)
  if (index !== -1) {
    activeWarnings.value.splice(index, 1)
  }
}

// 解析报警值 & 弹窗判断
const updatewarnValue = (id, newValue) => {
  const warning = warnings.value.find(w => w.id === id)
  if (warning) {
    // 反转二进制字符串方便低位访问
    const bits = parseInt(newValue, 16)
      .toString(2)
      .padStart(8, '0')
      .split('')
      .reverse()
    
    const triggers = {
      low: bits[0] === '1',
      high: bits[1] === '1',
      err: bits[2] === '1'
    }

    Object.entries(triggers).forEach(([type, isActive]) => {
      if (isActive && !warning[type]) {
        showDialog(type, warning.name, warning.id)
      }
      warning[type] = isActive
    })
  }
}
//处理接收到的 WebSocket 消息
bus.on('sendMsg', (rawData) => {
  try {
    // 1. 统一数据解析方式
    const parsedData = typeof rawData === 'string' ? JSON.parse(rawData) : rawData;
    
    // 2. 调试输出原始数据
    //console.log("收到原始数据:", parsedData);

    // 3. 类型检查和处理
    if (parsedData.type === 5) {
      const dataItems = Array.isArray(parsedData.data) ? parsedData.data : [parsedData.data];
      
      console.log("高压空气数据:", dataItems);
      
      // 4. 处理每个数据项
      dataItems.forEach(item => {
        const id = Number(item.id);
        const value = Number(item.data);
        
        // 5. 根据ID范围分配处理逻辑
        if (id < 15) {
          updatewarnValue(id, value.toFixed(2) + 'MPa');
        } else if (id >= 15 && id < 16) {
          updateFlowMeterValue(id, value.toFixed(2) + 'm³/h');
        } else if (id >= 16 && id < 17) {
          updateFlowMeterValue(id, value.toFixed(2) + 'MPa');
        } else if (id >= 17 && id < 18) {
          updateFlowMeterValue(id, value.toFixed(2) + '℃');
        } else if (id >= 18 && id < 19) {
          updateFlowMeterValue(id, value.toFixed(2) + '℃');
        } else if (id >= 19 && id < 20) {
          updateFlowMeterValue(id, value.toFixed(2) + 'm³/h');
        } else if (id >= 20 && id < 21) {
          updateFlowMeterValue(id, '大气压力' + value.toFixed(2) + 'kPa');
        } else if (id >= 21 && id < 22) {
          updateFlowMeterValue(id, '大气温度' + value.toFixed(2) + '℃');
        } else if (id >= 22 && id < 23) {
          updateFlowMeterValue(id, '大气湿度' + value.toFixed(2) + '%RH');
        }
      });
    }
  } catch (error) {
    console.error("数据处理失败:", error);
    console.error("错误数据内容:", rawData);
  }
});
//更新模拟量数据
const updateFlowMeterValue = (id, newValue) => {
  const simulateValue = simulateValues.value.find(fm => fm.id === id);
  if (simulateValue) {
    simulateValue.value = newValue;
    //console.log(newValue);
  }
};
</script>


<style scoped lang="scss">
.air {
  background-image: url('/images/air.png');
  ::v-deep(.custom-warning-dialog) {
    color: red;
  }
  ::v-deep(.el-dialog) {
    position: absolute !important;
    border: 2px solid #000;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
  ::v-deep(.el-dialog__header) {
    font-size: 18px;
    font-weight: bold;
    cursor: move;
  }
  /* ::v-deep(.el-dialog__body) {
    font-size: 16px;
    padding: 20px;
  } */
  ::v-deep(.el-dialog__footer) {
    text-align: right;
    padding: 10px 20px;
  }

  /* 确保对话框可见 */

  ::v-deep(.el-overlay) {
    pointer-events: none; /* 允许穿透点击 */
  }

  ::v-deep(.el-dialog.is-draggable) {
    pointer-events: auto;
  }

  .on-off {
    .icon {
      width: 0vw;
      height: 0vh;
    }
    .simulate-value15 {
      position: fixed !important;
      top: 81%;
      left: 19%;
    }

    .simulate-value16 {
      position: fixed !important;
      top: 53%;
      left: 50%;
    }

    .simulate-value17 {
      position: fixed !important;
      top: 10%;
      left: 57.5%;
    }

    .simulate-value18 {
      position: fixed !important;
      top: 10%;
      left: 61%;
    }

    .simulate-value19 {
      position: fixed !important;
      top: 53%;
      left: 42%;
    }
    .simulate-value20 {
      position: fixed !important;
      top: 12%;
      left: 87%;
    }

    .simulate-value21 {
      position: fixed !important;
      top: 15%;
      left: 87%;
    }

    .simulate-value22 {
      position: fixed !important;
      top: 18%;
      left: 87%;
    }
  }
}
</style>

